package com.frejoys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frejoys.common.dto.admin.*;
import com.frejoys.common.dto.app.CategoryIdDto;
import com.frejoys.common.dto.app.CodeDto;
import com.frejoys.common.dto.common.IdDto;
import com.frejoys.common.dto.store.CoreDataDto;
import com.frejoys.common.dto.store.StoreLngAndTelDto;
import com.frejoys.common.enums.*;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.service.AliStorageService;
import com.frejoys.common.util.AppConfigUtil;
import com.frejoys.common.util.CommonUtil;
import com.frejoys.common.util.SnowflakeUtil;
import com.frejoys.common.util.TimeUtil;
import com.frejoys.common.vo.admin.StoreAndCodeVo;
import com.frejoys.common.vo.admin.StoreIdAndNameListVo;
import com.frejoys.common.vo.app.StoreListInfoVo;
import com.frejoys.common.vo.app.StoreVo;
import com.frejoys.common.vo.common.AdcodeVo;
import com.frejoys.common.vo.store.CoreDataVo;
import com.frejoys.common.vo.store.MonthDataVo;
import com.frejoys.common.vo.store.StoreListVo;
import com.frejoys.dao.entity.*;
import com.frejoys.dao.mapper.*;
import com.frejoys.service.*;
import com.github.binarywang.wxpay.service.EcommerceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

// 店家
@Service
@RequiredArgsConstructor
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {

    private final StoreWalletService storeWalletService;

    private final StoreUserService storeUserService;

    private final StoreUserMapper storeUserMapper;

    private final GoodsMapper goodsMapper;

    private final StoreMapper storeMapper;

    private final AgentStoreService agentStoreService;

    private final StoreEnterService storeEnterService;

    private final AreaService areaService;

    private final StoreCodeService storeCodeService;

    private final CategoryMapper categoryMapper;

    private final AgentStoreMapper agentStoreMapper;

    private final UserMapper userMapper;

    private final StoreCodeMapper storeCodeMapper;

    private final AliStorageService aliStorageService;

    private final StoreWalletLogMapper storeWalletLogMapper;

    private final OrderMapper orderMapper;

    private final StoreSaleMapper storeSaleMapper;

    private final StoreStatisticsYearMapper storeStatisticsYearMapper;

    private final StoreStatisticsMonthMapper storeStatisticsMonthMapper;

    private final CommonService commonService;

    private final StoreActivityMapper storeActivityMapper;

    @Override
    public IPage<com.frejoys.common.vo.admin.StoreVo> listInfo(StoreListDto dto) {
        Page<Store> page = new Page<>(dto.getPage(), dto.getSize());

        List<Integer> storeIds = new ArrayList<>();
        IPage<com.frejoys.common.vo.admin.StoreVo> storeVoIPage = new Page<>();

        if (dto.getUserId() != 0){
            LambdaQueryWrapper<StoreUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(StoreUser::getStoreId).eq(StoreUser::getUserId,dto.getUserId());
            List<StoreUser> agentStores = storeUserMapper.selectList(wrapper);
            storeIds = agentStores.stream().map(StoreUser::getStoreId).toList();

        }
        if (dto.getUserId() == 0 || dto.getUserId() != 0 && !storeIds.isEmpty() ){
            storeVoIPage = baseMapper.getStoreListInfo(page,dto,storeIds);
        }
        List<com.frejoys.common.vo.admin.StoreVo> records = storeVoIPage.getRecords();

        if (!records.isEmpty()){

            List<Integer> ids = records.stream().map(com.frejoys.common.vo.admin.StoreVo::getId).toList();
            //查询用户信息
            LambdaQueryWrapper<AgentStore> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(AgentStore::getUserId,AgentStore::getStoreId).in(AgentStore::getStoreId,ids);
            List<AgentStore> storeList = agentStoreMapper.selectList(queryWrapper);
            Map<Integer, Long> storeIdAndUserIdMap = storeList.stream().collect(Collectors.toMap(AgentStore::getStoreId, AgentStore::getUserId));

            List<Long> userIds = storeList.stream().map(AgentStore::getUserId).toList();
            List<User> users = userMapper.getUserByIds(userIds);
            Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, user -> user));

            Map<String, String> areaMap = areaService.getNameMap();

            //查询支付码
            LambdaQueryWrapper<StoreCode> storeCodeWrapper = new LambdaQueryWrapper<>();
            storeCodeWrapper.select(StoreCode::getStoreId,StoreCode::getCode,StoreCode::getPayCode)
                    .eq(StoreCode::getType,EStoreCodType.online.getValue())
                    .in(StoreCode::getStoreId,ids);
            List<StoreCode> storeCodes = storeCodeMapper.selectList(storeCodeWrapper);
            Map<Integer, StoreCode> storeCodeMap = storeCodes.stream().collect(Collectors.toMap(StoreCode::getStoreId, storeCode -> storeCode));

            //查询品类名称
            List<Integer> categoryIds = records.stream().map(com.frejoys.common.vo.admin.StoreVo::getCategoryId).toList();
            LambdaQueryWrapper<Category> categoryWrapper = new LambdaQueryWrapper<>();
            categoryWrapper.select(Category::getName,Category::getId)
                    .in(Category::getId,categoryIds)
                    .eq(Category::getStatus,EStatus.on.getValue());
            List<Category> categorys = categoryMapper.selectList(categoryWrapper);
            Map<Integer, String> categoryNameMap = categorys.stream().collect(Collectors.toMap(Category::getId, Category::getName));

//            //查询店铺总收益
//            List<Integer> storeIdList = records.stream().map(com.frejoys.common.vo.admin.StoreVo::getId).toList();
//            LambdaQueryWrapper<StoreStatisticsYear> yearWrapper = new LambdaQueryWrapper<>();
//            yearWrapper.select(StoreStatisticsYear::getMoney,StoreStatisticsYear::getStoreId);
//            yearWrapper.in(StoreStatisticsYear::getStoreId,storeIdList);
//            List<StoreStatisticsYear> statisticsDays = storeStatisticsYearMapper.selectList(yearWrapper);
//
//            Map<Integer, List<StoreStatisticsYear>> yearMap = statisticsDays.stream().collect(Collectors.groupingBy(StoreStatisticsYear::getStoreId));

            records.forEach(storeVo -> {

                if (storeIdAndUserIdMap.containsKey(storeVo.getId())){
                    User user = userMap.get(storeIdAndUserIdMap.get(storeVo.getId()));
                    if (!ObjectUtil.isEmpty(user)){
                        storeVo.setPhone(user.getPhone());
                        storeVo.setNickname(user.getNickname());
                    }
                }
                if (storeCodeMap.containsKey(storeVo.getId())){
                    storeVo.setPayCodeUrl(AppConfigUtil.getUrlPrefix(storeCodeMap.get(storeVo.getId()).getPayCode(),EFileSize.qrcode.getValue()));
                }
                if (categoryNameMap.containsKey(storeVo.getCategoryId())){
                    storeVo.setCategoryName(categoryNameMap.get(storeVo.getCategoryId()));
                }

                storeVo.setCityName(areaMap.get(storeVo.getCity()));
                storeVo.setProvinceName(areaMap.get(storeVo.getProvince()));
                storeVo.setDistrictName(areaMap.get(storeVo.getDistrict()));
                storeVo.setCoverUrl(AppConfigUtil.getUrlPrefix(storeVo.getCover()));
                storeVo.setLogoUrl(AppConfigUtil.getUrlPrefix(storeVo.getLogo(),EFileSize.logo.getValue()));
                storeVo.setCoverShowUrl(AppConfigUtil.getUrlPrefix(storeVo.getCoverShow()));
            });
        }

        return storeVoIPage;
    }


    //主页店铺列表
    @Override
    public List<StoreListVo> storeAppListInfo(StoreLngAndTelDto storeLngAndTelDto) {
        Page<Store> page = new Page<>(storeLngAndTelDto.getPage(),storeLngAndTelDto.getSize());
        page.setSearchCount(false);
        List<StoreListVo> storeListVos = Collections.emptyList();
        if (EStoreType.brand.getValue().equals(storeLngAndTelDto.getType())) {
            List<Store> stores = listBrandStore(page);
            storeListVos = BeanUtil.copyToList(stores, StoreListVo.class);
        } else if (storeLngAndTelDto.getLat()!=null && storeLngAndTelDto.getLng()!=null ){
            List<Store> stores = listInfoNearby(page, storeLngAndTelDto.getLng(),storeLngAndTelDto.getLat());
            // 附近没有商家则查所有
//            if (stores.isEmpty()) {
//                LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
//                queryWrapper.eq(Store::getShelves, EShelves.onSale.getValue());
//                queryWrapper.eq(Store::getType, storeLngAndTelDto.getType());
//                queryWrapper.eq(Store::getStatus, EStatus.on.getValue());
//                stores = list(page, queryWrapper);
//            }
            storeListVos = BeanUtil.copyToList(stores, StoreListVo.class);
        }
        if (!storeListVos.isEmpty()){
            for (StoreListVo storeListVo : storeListVos) {
                storeListVo.setCover(AppConfigUtil.getUrlPrefix(storeListVo.getCover()));
            }
        }
        return storeListVos;
    }


    //店铺详情页
    @Override
    public StoreVo storeDetails(CodeDto dto) {

        LambdaQueryWrapper<Store> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Store::getId, dto.getId());
        wrapper.eq(Store::getShelves, EShelves.onSale.getValue());
        wrapper.eq(Store::getStatus, EStatus.on.getValue());
        Store store = getOnly(wrapper);

        if (store == null) {
            return null;
        }

        //查询品类
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Category::getName).eq(Category::getId,store.getCategoryId());
        Category category = categoryMapper.selectOne(queryWrapper);

        //查询距离
        double distance = commonService.calculateDistance(dto.getLat(), dto.getLng(), store.getLat(), store.getLng());

        //查询地址
        Map<String, String> areaMap = areaService.getNameMap();
        StoreVo storeVo = new StoreVo();

        storeVo.setId(store.getId());
        storeVo.setDistance(distance);
        storeVo.setName(store.getName());
        storeVo.setCategoryId(store.getCategoryId());
        storeVo.setCategoryName(ObjectUtil.isEmpty(category) ? "" : category.getName());
        storeVo.setLogo(AppConfigUtil.getUrlPrefix(store.getLogo(), EFileSize.logo.getValue()));
        storeVo.setCover(AppConfigUtil.getUrlPrefix(store.getCover()));
        storeVo.setCoverShow(AppConfigUtil.getUrlPrefix(store.getCoverShow()));
        storeVo.setProvinceName(areaMap.get(store.getProvince()));
        storeVo.setCityName(areaMap.get(store.getCity()));
        storeVo.setDistrictName(areaMap.get(store.getDistrict()));
        storeVo.setStreet(store.getStreet());
        storeVo.setAddress(store.getAddress());
        storeVo.setLng(store.getLng());
        storeVo.setLat(store.getLat());
        storeVo.setTel(store.getTel());
        storeVo.setStartTime(store.getStartTime());
        storeVo.setEndTime(store.getEndTime());
        storeVo.setCreateTime(store.getCreateTime());
        return storeVo;
    }

    @Override
    public List<Store> listBusinessStore(StoreListDto dto, Long userId) {

        if (userId == null) {
            return new ArrayList<>();
        }

        // 查询商家拥有的店铺
        LambdaQueryWrapper<StoreUser> storeUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        storeUserLambdaQueryWrapper.select(StoreUser::getStoreId);
        storeUserLambdaQueryWrapper.eq(StoreUser::getUserId, userId);
        List<StoreUser> storeUsers = storeUserMapper.selectList(storeUserLambdaQueryWrapper);
        List<Integer> storeIds = storeUsers.stream().map(StoreUser::getStoreId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(storeIds)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Store::getId, storeIds);
        queryWrapper.eq(dto.getCategoryId() != null, Store::getCategoryId, dto.getCategoryId());
        queryWrapper.eq(StrUtil.isNotEmpty(dto.getName()), Store::getName, dto.getName());
        Page<Store> page = new Page<>(dto.getPage(), dto.getSize());
        page.setSearchCount(false);
        return baseMapper.selectList(page, queryWrapper);
    }

    @Override
    public List<Store> listInfoNearby(Page<Store> page,Double lng, Double lat) {
        return baseMapper.selectNearby(page,lng, lat);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Store addInfo(StoreAddDto dto, Long userId) {
        Store store = BeanUtil.copyProperties(dto, Store.class);

        AdcodeVo adcodeVo = areaService.getProvinceCityDistrict(dto.getDistrict());

        store.setCity(adcodeVo != null ? adcodeVo.getCity() : null);
        store.setProvince(adcodeVo != null ? adcodeVo.getProvince() : null);

        store.setCreateTime(TimeUtil.unixTime());
        store.setUpdateTime(TimeUtil.unixTime());
        save(store);
        // 添加店铺钱包
        LambdaQueryWrapper<StoreWallet> walletQw = new LambdaQueryWrapper<>();
        walletQw.eq(StoreWallet::getStoreId,store.getId());
        if (!storeWalletService.exists(walletQw)) {
            StoreWallet storeWallet = new StoreWallet();
            storeWallet.setStoreId(store.getId());
            storeWallet.setMoney(BigDecimal.ZERO);
            storeWalletService.save(storeWallet);
        }
        // 关联用户与店铺
        StoreUser storeUser = new StoreUser();
        storeUser.setUserId(userId);
        storeUser.setStoreId(store.getId());
        storeUser.setRole(EStoreUserType.owner.getValue());
        storeUserService.save(storeUser);

        Long agentUserId = storeEnterService.getAgentUserId(userId);
        // 未找到当前用户的代理人
        if (agentUserId == null) {
            throw new GeneralException(HttpStatus.agentError);
        }

        // 创建店铺代理人
        agentStoreService.addInfo(agentUserId, userId, store.getId());

        storeCodeService.addStoreCode(store.getId(), SnowflakeUtil.appNextId(), null, EStoreCodType.online.getValue());

        return store;
    }

    @Override
    public boolean upInfo(StoreUpDto dto) {
        boolean storeOnSale = baseMapper.exists(Wrappers.<Store>lambdaQuery().eq(Store::getId, dto.getId())
                .and(qw -> {
                    qw.eq(Store::getShelves, EShelves.onSale.getValue());
                    qw.or();
                    qw.eq(Store::getShelves, EShelves.applyfor.getValue());
                }));
        if (storeOnSale) {
            throw new GeneralException(HttpStatus.onSaleEditError);
        }
        LambdaUpdateWrapper<Store> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Store::getId, dto.getId());
        if (StrUtil.isNotEmpty(dto.getName())) {
            wrapper.set(Store::getName, dto.getName());
        }
        if (dto.getCategoryId() != null) {
            wrapper.set(Store::getCategoryId, dto.getCategoryId());
        }
        if (StrUtil.isNotEmpty(dto.getLogo())) {
            wrapper.set(Store::getLogo, dto.getLogo());
        }
        if (StrUtil.isNotEmpty(dto.getCover())) {
            wrapper.set(Store::getCover, dto.getCover());
        }

        if (StrUtil.isNotEmpty(dto.getDistrict())) {
            LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(Store::getDistrict);
            queryWrapper.eq(Store::getId,dto.getId());
            Store store = getOnly(queryWrapper);
            if (store!=null && !dto.getDistrict().equals(store.getDistrict())) {
                wrapper.set(Store::getDistrict,dto.getDistrict());
                AdcodeVo adcodeVo = areaService.getProvinceCityDistrict(dto.getDistrict());
                if (adcodeVo != null) {
                    wrapper.set(Store::getProvince, adcodeVo.getProvince());
                    wrapper.set(Store::getCity, adcodeVo.getCity());
                }
            }
        }

//        if (StrUtil.isNotEmpty(dto.getStreet())) {
//            wrapper.set(Store::getStreet, dto.getStreet());
//        }
        if (StrUtil.isNotEmpty(dto.getAddress())) {
            wrapper.set(Store::getAddress, dto.getAddress());
        }
        if (StrUtil.isNotEmpty(dto.getCoverShow())) {
            wrapper.set(Store::getCoverShow, dto.getCoverShow());
        }

        if (dto.getLng() != null) {
            wrapper.set(Store::getLng, dto.getLng());
        }
        if (dto.getLat() != null) {
            wrapper.set(Store::getLat, dto.getLat());
        }
        if (StrUtil.isNotEmpty(dto.getTel())) {
            wrapper.set(Store::getTel, dto.getTel());
        }
//        if (dto.getType() != null) {
//            wrapper.set(Store::getType, dto.getType());
//        }
//        if (dto.getShelves()!=null) {
//            wrapper.set(Store::getShelves, dto.getShelves());
//        }
        if (dto.getStartTime() != null && dto.getEndTime() != null) {
            wrapper.set(Store::getStartTime, dto.getStartTime());
            wrapper.set(Store::getEndTime, dto.getEndTime());
        }
        wrapper.set(Store::getUpdateTime, TimeUtil.unixTime());
        return update(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delInfo(IdDto dto) {
        // 验证店铺是否存在上架商品
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Goods::getId)
                    .eq(Goods::getStoreId,dto.getId())
                    .eq(Goods::getShelves,EShelves.onSale.getValue());

        List<Goods> goodsList = goodsMapper.selectList(queryWrapper);

        if (!goodsList.isEmpty()){
            throw new GeneralException(HttpStatus.soldOutError);
        }
        // 服务店铺关闭
        agentStoreService.delInfo(dto.getId());

        LambdaUpdateWrapper<Store> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Store::getId, dto.getId());
        wrapper.set(Store::getStatus, EStatus.off.getValue());
        wrapper.set(Store::getUpdateTime, TimeUtil.unixTime());
        return update(wrapper);
    }

    @Override
    public List<Store> listBrandStore(Page<Store> page) {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Store::getShelves, EShelves.onSale.getValue());
        queryWrapper.eq(Store::getType, EStoreType.brand.getValue());
        queryWrapper.eq(Store::getStatus, EStatus.on.getValue());
        return baseMapper.selectList(page,queryWrapper);
    }


    @Override
    public Map<Integer, String> getIdNameMap() {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Store::getId, Store::getName);
        queryWrapper.eq(Store::getShelves, EShelves.onSale.getValue());
        queryWrapper.eq(Store::getStatus, EStatus.on.getValue());
        List<Store> storeList = storeMapper.selectList(queryWrapper);
        Map<Integer, String> storeIdNameMap = storeList.stream().collect(Collectors.toMap(Store::getId, Store::getName));
        return storeIdNameMap;
    }

    @Override
    public Map<Integer, String> getIdNameMap(List<Integer> storeIds) {
        Map<Integer, String> storeIdNameMap = new HashMap<>();

        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Store::getId, Store::getName);
        queryWrapper.in(!CollectionUtils.isEmpty(storeIds),Store::getId, storeIds);
        List<Store> storeList = storeMapper.selectList(queryWrapper);

        if (!storeList.isEmpty()) {
            storeIdNameMap = storeList.stream().collect(Collectors.toMap(Store::getId, Store::getName));
        }
        return storeIdNameMap;
    }

    @Override
    public List<StoreListInfoVo> categoryIdStoreList(CategoryIdDto dto) {
        Page<Store> page = new Page<>(dto.getPage(),dto.getSize());
        page.setSearchCount(false);

        List<StoreListInfoVo> storeList= baseMapper.categoryIdStoreList(page,dto);

        if (!storeList.isEmpty()){
            Map<String, String> areaMap = areaService.getNameMap();
            List<Integer> categoryIds = storeList.stream().map(StoreListInfoVo::getCategoryId).distinct().toList();

            //查询品类名称
            LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(Category::getName,Category::getId)
                    .in(Category::getId,categoryIds)
                    .eq(Category::getStatus,EStatus.on.getValue());
            List<Category> categorys = categoryMapper.selectList(queryWrapper);
            Map<Integer, String> categoryNameMap = categorys.stream().collect(Collectors.toMap(Category::getId, Category::getName));

            storeList.forEach(store -> {

                store.setCityName(areaMap.get(store.getCity()));
                store.setDistrictName(areaMap.get(store.getDistrict()));
                store.setProvinceName(areaMap.get(store.getProvince()));
                store.setCover(AppConfigUtil.getUrlPrefix(store.getCover()));
                if (categoryNameMap.containsKey(store.getCategoryId())){
                    store.setCategoryName(categoryNameMap.get(store.getCategoryId()));
                }
            });
        }
        return storeList;
    }



    @Override
    public IPage<StoreAndCodeVo> storeListInfo(StoreListDto dto) {
        Page<Store> page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<Store> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Store::getId,Store::getName,Store::getLogo,Store::getTel);
        if (StrUtil.isNotEmpty(dto.getName())){
            List<Store> stores = baseMapper.getStoreNameById(dto.getName());
            if (stores.isEmpty()){
                return new Page<>();
            }
            List<Integer> storeIds = stores.stream().map(Store::getId).toList();
            wrapper.in(Store::getId,storeIds);
        }
        if (StrUtil.isNotEmpty(dto.getTel())){
            wrapper.eq(Store::getTel,dto.getTel());
        }
        wrapper.orderByDesc(Store::getCreateTime);
        Page<Store> storePage = baseMapper.selectPage(page, wrapper);
        IPage<StoreAndCodeVo> storeAndCodeVoIPage = storePage.convert(store -> BeanUtil.copyProperties(store, StoreAndCodeVo.class));
        List<StoreAndCodeVo> list = storeAndCodeVoIPage.getRecords();

        if (!list.isEmpty()){
            List<Integer> ids = list.stream().map(StoreAndCodeVo::getId).toList();

            LambdaQueryWrapper<StoreCode> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(StoreCode::getStoreId,StoreCode::getCode)
                    .eq(StoreCode::getType,EStoreCodType.offLine.getValue())
                    .in(StoreCode::getStoreId,ids);
            List<StoreCode> storeCodes = storeCodeMapper.selectList(queryWrapper);
            Map<Integer, StoreCode> storeCodeMap = storeCodes.stream().collect(Collectors.toMap(StoreCode::getStoreId, storeCode -> storeCode));

            list.forEach(vo ->{
                if (storeCodeMap.containsKey(vo.getId())){
                    vo.setCode(storeCodeMap.get(vo.getId()).getCode());
                    vo.setPayCode(aliStorageService.createQrCodeLogoPayImage(String.valueOf(storeCodeMap.get(vo.getId()).getCode())));
                }
                vo.setLogoUrl(AppConfigUtil.getUrlPrefix(vo.getLogo(),EFileSize.logo.getValue()));
            });
        }
        return storeAndCodeVoIPage;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean upStoreShelves(UpShelvesDto dto) {

        if (dto.getShelves() == EShelves.onSale.getValue() || dto.getShelves() == EShelves.offShelf.getValue()){

            LambdaQueryWrapper<Store> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(Store::getId)
                    .eq(Store::getId,dto.getId());
            Store store = getOnly(wrapper);
            //校验店铺是否存在
            if (ObjectUtil.isEmpty(store)){
                throw new GeneralException(HttpStatus.storeNotFound);
            }

            if (dto.getShelves() == EShelves.onSale.getValue()){

                //校验店铺是否有上架的商品和活动
                verifyStoreGoodsAndActivity(dto.getId());
            }
            //修改上下架状态
            LambdaUpdateWrapper<Store> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Store::getShelves,dto.getShelves())
                    .set(Store::getUpdateTime,TimeUtil.unixTime())
                    .eq(Store::getId,dto.getId());
            baseMapper.update(updateWrapper);

            //修改商品表店铺状态
            LambdaUpdateWrapper<Goods> goodsWrapper = new LambdaUpdateWrapper<>();
            goodsWrapper.set(Goods::getStoreShelves,dto.getShelves())
                    .eq(Goods::getStoreId,dto.getId());
            goodsMapper.update(goodsWrapper);
        }
        return true;
    }



    @Override
    public MonthDataVo monthData(Long userId) {
        MonthDataVo vo = new MonthDataVo();

        if (userId == null){
            return vo;
        }

        LambdaQueryWrapper<StoreUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(StoreUser::getStoreId)
                .eq(StoreUser::getUserId,userId);
        List<StoreUser> storeUsers = storeUserMapper.selectList(wrapper);

        if (!storeUsers.isEmpty()){
            BigDecimal turnoverMoney = BigDecimal.ZERO;
            Integer turnoverOrderCount = 0;
            Integer waitVerifyCount = 0;

            List<Integer> storeIds = storeUsers.stream().map(StoreUser::getStoreId).toList();

            //当月开始时间
            int startTime = TimeUtil.beginOfMonth(TimeUtil.unixTime());

            //当月结束时间
            int endTime = TimeUtil.endOfMonth(TimeUtil.unixTime());

            //查出本月收益
            LambdaQueryWrapper<StoreStatisticsMonth> monthWrapper = new LambdaQueryWrapper<>();
            monthWrapper.select(StoreStatisticsMonth::getMoney)
                    .in(StoreStatisticsMonth::getStoreId,storeIds)
                    .eq(StoreStatisticsMonth::getYm,Integer.valueOf(TimeUtil.formatYm(TimeUtil.unixTime())));
            List<StoreStatisticsMonth> storeStatisticsMonths = storeStatisticsMonthMapper.selectList(monthWrapper);

//            LambdaQueryWrapper<StoreSale> saleWrapper = new LambdaQueryWrapper<>();
//            saleWrapper.select(StoreSale::getMoney)
//                    .in(StoreSale::getStoreId,storeIds)
//                    .ge(StoreSale::getCreateTime,startTime)
//                    .le(StoreSale::getCreateTime,endTime);
//            List<StoreSale> storeSaleList = storeSaleMapper.selectList(saleWrapper);

            if (!storeStatisticsMonths.isEmpty()){
                for (StoreStatisticsMonth storeStatisticsMonth:storeStatisticsMonths) {
                    turnoverMoney = CommonUtil.bigDecimalAdd(turnoverMoney,storeStatisticsMonth.getMoney());
                }
            }

            //查询本月 已结算 和待核销订单量
            LambdaQueryWrapper<Order> orderWrapper = new LambdaQueryWrapper<>();
            orderWrapper.select(Order::getVerify,Order::getIsScore)
                    .eq(Order::getPayStatus,EPayStatus.finish.getValue())
                    .eq(Order::getStatus,EStatus.on.getValue())
                    .ge(Order::getCreateTime,startTime)
                    .le(Order::getCreateTime,endTime)
                    .in(Order::getStoreId,storeIds);
            List<Order> orders = orderMapper.selectList(orderWrapper);

            if (!orders.isEmpty()){

                for (Order order:orders){

                    if (order.getVerify() == EVerify.wait.getValue()){
                        waitVerifyCount += 1;
                    }
                    if (order.getVerify() >= EVerify.finish.getValue()){
                        turnoverOrderCount += 1;
                    }
                }
            }
            vo.setTurnoverMoney(turnoverMoney);
            vo.setTurnoverOrderCount(turnoverOrderCount);
            vo.setWaitVerifyCount(waitVerifyCount);
        }
        return vo;
    }


    @Override
    public List<StoreIdAndNameListVo> storeNameListInfo(Long userId) {

        List<StoreIdAndNameListVo> list = new ArrayList<>();

        LambdaQueryWrapper<StoreUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(StoreUser::getStoreId)
                .eq(StoreUser::getUserId,userId);
        List<StoreUser> storeUsers = storeUserMapper.selectList(wrapper);

        if (!storeUsers.isEmpty()){

            List<Integer> storeIds = storeUsers.stream().map(StoreUser::getStoreId).toList();
            List<Store> stores = baseMapper.getStoreNameList(storeIds);

            if (!stores.isEmpty()){
                stores.forEach(store -> {
                    StoreIdAndNameListVo vo = new StoreIdAndNameListVo();
                    vo.setId(store.getId());
                    vo.setName(store.getName());
                    vo.setLogo(store.getLogo());
                    vo.setLogoUrl(AppConfigUtil.getUrlPrefix(store.getLogo(),EFileSize.logo.getValue()));
                    list.add(vo);
                });
            }

        }
        return list;
    }


    @Override
    public CoreDataVo coreData(CoreDataDto dto) {

        CoreDataVo vo = new CoreDataVo();
        if (dto.getStoreId() != null){

            //开始时间
            Integer startTime = 0;
            //结束时间
            Integer endTime = 0;
            //成交金额
            BigDecimal turnoverMoney = BigDecimal.ZERO;
            //平均价
            BigDecimal averageMoney = BigDecimal.ZERO;
            //成交订单量
            Integer turnoverOrderCount = 0;
            //待核销订单量
            Integer waitVerifyCount = 0;
            //退款订单量
            Integer refundOrderCount =0;

            List<StoreSale> storeSales = new ArrayList<>();
            List<Order> orders = new ArrayList<>();

            if (dto.getType() == ECoreDataType.today.getValue() || dto.getType() == ECoreDataType.freedomDay.getValue()){
                startTime = TimeUtil.beginOfDay(TimeUtil.unixTime(dto.getTime()));
                endTime = TimeUtil.endOfDay(TimeUtil.unixTime(dto.getTime()));

                //查询成交金额
                storeSales = storeSaleMapper.getMonetList(dto.getStoreId(),startTime,endTime);

                //查询订单
                orders = orderMapper.getOrderVerifyAndIsScore(dto.getStoreId(),startTime,endTime,EStatus.on.getValue());

            }else if (dto.getType() == ECoreDataType.yesterday.getValue()){
                startTime = TimeUtil.beginOfDay((int) (TimeUtil.unixTime(dto.getTime()) - TimeUtil.daySecond));
                endTime = TimeUtil.endOfDay((int) (TimeUtil.unixTime(dto.getTime()) - TimeUtil.daySecond));

                //查询成交金额
                storeSales = storeSaleMapper.getMonetList(dto.getStoreId(),startTime,endTime);

                //查询订单
                orders = orderMapper.getOrderVerifyAndIsScore(dto.getStoreId(),startTime,endTime,EStatus.on.getValue());

            }else if (dto.getType() == ECoreDataType.sevenDays.getValue()){
                startTime = TimeUtil.beginOfDay((int) (TimeUtil.unixTime(dto.getTime()) - TimeUtil.daySecond * 7));
                endTime = TimeUtil.endOfDay(TimeUtil.unixTime(dto.getTime()));

                //查询成交金额
                storeSales = storeSaleMapper.getMonetList(dto.getStoreId(),startTime,endTime);

                //查询订单
                orders = orderMapper.getOrderVerifyAndIsScore(dto.getStoreId(),startTime,endTime,EStatus.on.getValue());

            }else if (dto.getType() == ECoreDataType.thirtyDays.getValue()){
                startTime = TimeUtil.beginOfDay((int) (TimeUtil.unixTime(dto.getTime()) - TimeUtil.daySecond * 30));
                endTime = TimeUtil.endOfDay(TimeUtil.unixTime(dto.getTime()));

                //查询成交金额
                storeSales = storeSaleMapper.getMonetList(dto.getStoreId(),startTime,endTime);

                //查询订单
                orders = orderMapper.getOrderVerifyAndIsScore(dto.getStoreId(),startTime,endTime,EStatus.on.getValue());

            }
            //查询订单成交总量
            Integer orderCount = orderMapper.orderCount(dto.getStoreId(),EVerify.finish.getValue(), EStatus.on.getValue());

            //查询店铺年收益
            LambdaQueryWrapper<StoreStatisticsYear> yearWrapper = new LambdaQueryWrapper<>();
            yearWrapper.select(StoreStatisticsYear::getMoney).eq(StoreStatisticsYear::getStoreId,dto.getStoreId());
            List<StoreStatisticsYear> storeStatisticsYears = storeStatisticsYearMapper.selectList(yearWrapper);

            BigDecimal moneyAll = BigDecimal.ZERO;
            if (!storeStatisticsYears.isEmpty()){
                for (StoreStatisticsYear s:storeStatisticsYears) {
                    moneyAll = CommonUtil.bigDecimalAdd(moneyAll,s.getMoney());
                }
            }

            //成交金额
            if (!storeSales.isEmpty()){
                for (StoreSale storeSale:storeSales) {
                    turnoverMoney = CommonUtil.bigDecimalAdd(turnoverMoney,storeSale.getMoney());
                }
            }

            //查询订单量
            if (!orders.isEmpty()){
                for (Order order:orders) {
                    //待核销订单
                    if (order.getVerify() == EVerify.wait.getValue()){
                        waitVerifyCount += 1;
                    }
                    //成交订单
                    if (order.getVerify() == EVerify.finish.getValue() || order.getVerify() == EVerify.rebate.getValue()){
                        turnoverOrderCount += 1;
                    }
                    //退款订单
                    if (order.getPayStatus() == EPayStatus.refund.getValue()){
                        refundOrderCount += 1;
                    }
                }
            }
            //计算平均价
            if (turnoverMoney != BigDecimal.ZERO && turnoverOrderCount != 0){
                averageMoney = CommonUtil.bigDecimalDivide(turnoverMoney, new BigDecimal(turnoverOrderCount));
            }

            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
            vo.setTurnoverOrderCount(turnoverOrderCount);
            vo.setWaitVerifyCount(waitVerifyCount);
            vo.setRefundOrderCount(refundOrderCount);
            vo.setAverageMoney(CommonUtil.bigDecimalRoundDown(averageMoney));
            vo.setTurnoverMoney(CommonUtil.bigDecimalRoundDown(turnoverMoney));
            vo.setMoneyAll(moneyAll);
            vo.setOrderCount(orderCount);
        }
        return vo;
    }



    @Override
    public IPage<StoreIdAndNameListVo> storeNameList(StoreIdAndNameDto dto) {
        Page page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<Store> wrapper = new LambdaQueryWrapper<>();
        if (dto.getStoreId() != null){
            wrapper.eq(Store::getId,dto.getStoreId());
        }
        if (StrUtil.isNotEmpty(dto.getName())){
            wrapper.like(Store::getName,dto.getName());
        }
        wrapper.orderByDesc(Store::getUpdateTime);
        Page<Store> storePage = baseMapper.selectPage(page, wrapper);
        IPage<StoreIdAndNameListVo> storeIPage = storePage.convert(store -> BeanUtil.copyProperties(store, StoreIdAndNameListVo.class));
        List<StoreIdAndNameListVo> storeList = storeIPage.getRecords();

        if (!storeList.isEmpty()){

            storeList.forEach(store -> {
                store.setLogoUrl(AppConfigUtil.getUrlPrefix(store.getLogo(),EFileSize.logo.getValue()));
                });
            }

        return storeIPage;
    }


    @Override
    public boolean verifyStoreGoodsAndActivity(Integer storeId) {
        //校验是否有上架的商品
        LambdaQueryWrapper<Goods> goodsWrapper = new LambdaQueryWrapper<>();
        goodsWrapper.select(Goods::getId)
                .eq(Goods::getStoreId,storeId)
                .eq(Goods::getShelves,EShelves.onSale.getValue())
                .eq(Goods::getStatus,EStatus.on.getValue());
        if (!goodsMapper.exists(goodsWrapper)){
            throw new GeneralException(HttpStatus.anOrderError);
        }

        //校验是否有上架的活动
        LambdaQueryWrapper<StoreActivity> storeActivityWrapper = new LambdaQueryWrapper<>();
        storeActivityWrapper.select(StoreActivity::getId)
                .eq(StoreActivity::getStoreId,storeId)
                .eq(StoreActivity::getShelves,EShelves.onSale.getValue())
                .le(StoreActivity::getStartTime, TimeUtil.unixTime())
                .ge(StoreActivity::getEndTime,TimeUtil.unixTime())
                .eq(StoreActivity::getStatus,EStatus.on.getValue());
        if (!storeActivityMapper.exists(storeActivityWrapper)){
            throw new GeneralException(HttpStatus.anStoreActivityError);
        }
        return false;
    }

}